#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
from common import *
import config

def createmkv(outputFile, files):
    cmd = '%s -o "%s"' % (config.toolPaths['mkvmerge'], outputFile)
    if os.path.exists('chapters.xml'):
        if len(open('chapters.xml').read()) > 0:
            cmd += ' --chapters chapters.xml'

    if (type( files ) == dict):
        files = files.values()
    for tomkv in files:
        if tomkv.has_key('language'):
            cmd += ' --language 0:%s' % (tomkv['language'])

        if tomkv.has_key('encodedfile'):
            fname = tomkv['encodedfile']
        else:
            fname = tomkv['fname']
        if fname.endswith('.aac'):
            cmd += ' --aac-is-sbr 0'
        elif fname.endswith("_chapters.txt"):
            cmd += ' --chapters'

        cmd += ' "%s"' % (fname)

    execute(cmd)

def oldcreatemkv(outputFile, streams):
    cmd = '%s -o "%s"' % (config.toolPaths['mkvmerge'], outputFile)
    if os.path.exists('chapters.xml'):
        if len(open('chapters.xml').read()) > 0:
            cmd += ' --chapters chapters.xml'

    for stream in streams:
        s = streams[stream]
        timeCodeFile = 'tc-track%s.txt' % (stream)
        if os.path.exists(timeCodeFile):
                cmd += ' --timecodes 0:%s' % (timeCodeFile)

        if s.has_key('language'):
            cmd += ' --language 0:%s' % (s['language'])

        if s['type'] in ['Video', 'video']:
            cmd += ' "%s"' % (s['encodedfile'])
        elif s['type'] in ['Audio', 'audio']:
            audioFile = s['encodedfile']
            if audioFile.endswith('.aac'):
                cmd += ' --aac-is-sbr 0'
            cmd += ' "%s"' % (audioFile)
        elif s['type'] in ['Subpict.', 'Subtitle', 'subtitles']:
            for fname in s['fname']:
                if fname.endswith('idx') or fname.endswith('srt'):
                    cmd += ' "%s"' % (fname)
                    break

    execute(cmd)

